<template>
    <main-layout title="管理采购单" :showHome="true" :showNew="true">
        <div class="page-container">
            <header class="my-header">
                <input type="text" placeholder="请输入项目名称进行查询">
                <van-dropdown-menu class="purchase-dropdown">
                    <van-dropdown-item v-model="queryObj.state" :options="stateList" />
                </van-dropdown-menu>
                <i class="icon"></i>
            </header>
            <section>
                <ul @scroll="scrollEvt" class="page-list-box">
                    <van-swipe-cell class="item" v-for="item in list" :key="item.id">
                        <div @click="$router.push({path: '/purchase/detail', query: {id: item.id}})">
                          <span class="span itemTitle">{{item.projectName}}
                              <em>{{item.state}}</em>
                          </span>
                          <span class="span">创建人：{{item.createName}}</span>
                          <span class="span">创建日期： {{item.createTime | df('MM月dd日 hh时mm分')}}</span>
                          <span class="span">材料：{{item.materialName}}--{{item.materialWeight}}--{{item.materialUnit}}</span>
                        </div>
                        <template #right>
                            <van-button v-if="item.state === '新建'" class="my-btn" square type="danger" text="删除" />
                            <van-button v-if="item.state === '新建'" class="my-btn" square type="primary" text="编辑" />
                            <van-button @click="approveEvt(item)" v-if="item.state === '新建'" class="my-btn" square type="warning" text="确认" />
                            <van-button @click="approveEvt(item)" v-if="item.state === '确认'" class="my-btn" square type="primary" text="在途" />
                            <van-button @click="approveEvt(item)" v-if="item.state === '在途'" class="my-btn" square type="primary" text="完成" />
                            <van-button v-if="item.state === '完成'" class="my-btn" square type="primary" color="#7232dd" text="付款" />
                        </template>
                    </van-swipe-cell>
                    <li>
                        <span v-if="loading" class="loading">加载中...</span>
                        <!-- 加载完成以后，如果有更多数据，则显示第一个，否则显示第二个 -->
                        <span v-if="!loading && hasMore" class="loading">上滑加载更多</span>
                        <span v-if="!loading && !hasMore" class="loading">我是有底线的~~</span>
                    </li>
                </ul>
            </section>
        </div>
        <!-- 确认/在途/完成 弹出框 -->
        <van-popup v-model="approveShow" position="bottom" :style="{ height: '420px' }" >
            <p style="font-size: .7rem; padding: 0 10px;">审批意见</p>
            <van-steps :active="active" active-icon="success" active-color="#38f">
                <van-step v-for="it in stepList" :key="it.text">{{it.value}}</van-step>
            </van-steps>
            <van-form @submit="onSubmit">
                <van-field name="radio" label="是否同意？">
                    <template #input>
                        <van-radio-group v-model="approveObj.isReject" direction="horizontal">
                        <van-radio :name="false" checked-color="#ff5b02">通过</van-radio>
                        <van-radio :name="true" checked-color="#ff5b02">驳回</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field v-model="approveObj.userName"
                    readonly
                    label="审批人"/>
                <van-field
                    v-model="approveObj.remark"
                    type="textarea"
                    label="审批意见"
                    placeholder="请输入审批意见"
                    :rules="[{ required: true }]"
                />
                <div style="margin: 16px;">
                    <van-button round block type="info" native-type="submit">提交</van-button>
                </div>
                <div style="margin: 16px;">
                    <van-button @click="approveShow = false" round block type="primary" native-type="button">关闭</van-button>
                </div>
            </van-form>
        </van-popup>
    </main-layout>
</template>

<script>
import { puchaseListApi, purchaseFlowApi } from '../../apis/puchaseApi'
const stepList = [
  { text: '新建', value: '新建' },
  { text: '确认', value: '确认' },
  { text: '在途', value: '在途' },
  { text: '完成', value: '完成' }
]
export default {
  data () {
    return {
      list: [],
      loading: true,
      hasMore: true,
      queryObj: {
        projectName: '',
        state: '',
        page: 1,
        size: 5
      },
      stepList,
      stateList: [
        { text: '全部', value: '' },
        ...stepList,
        { text: '作废', value: '作废' }
      ],
      approveShow: false,
      approveObj: {
        id: '',
        isReject: false,
        userId: '',
        userName: '',
        remark: ''
      },
      approveState: ''
    }
  },
  computed: {
    userInfo () {
      return this.$store.getters['common/userInfo']
    },
    active () {
      return this.stepList.findIndex(it => it.text === this.approveState) + 1
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 获取页面数据的方法
    async getList () {
      const result = await puchaseListApi(this.queryObj)
      if (result.code === 200) {
        this.list = this.list.concat(result.data.rows)
        this.hasMore = this.queryObj.page * this.queryObj.size < result.data.total
      }

      setTimeout(() => {
        this.loading = false
      })
    },
    // 滚动加载更多
    scrollEvt (evt) {
      const isBottom = (evt.target.clientHeight + evt.target.scrollTop + 20) > evt.target.scrollHeight
      if (isBottom && !this.loading && this.hasMore) {
        // 需要查询下页数据，开启节流标识，调用数据接口
        this.queryObj.page += 1
        this.loading = true
        this.getList()
      }
    },
    // 审批事件
    approveEvt (item) {
      // 找到当前需要进行的环节，根据这个环节来定义权限
      // 确认需要是审批人员才能执行，其它都是只有创建者才能执行
      const idx = this.stepList.findIndex(it => it.text === item.state) + 1
      const name = this.stepList[idx].value
      console.log(idx)
      console.log(name)
      // if (name === '确认' && !item.nextId.includes(this.userInfo.id)) {
      if (!item.nextId.includes(this.userInfo.id)) {
        this.$toast.fail('您不具备该订单的操作权限')
        return
      }
      // 对弹出层中的数据进行重置
      this.approveObj.id = item.id
      this.approveObj.isReject = false
      this.approveObj.userId = this.userInfo.id
      this.approveObj.userName = this.userInfo.name
      this.approveObj.remark = ''
      this.approveState = item.state

      // 打开弹出框
      this.approveShow = true
    },
    // 审批提交事件
    async onSubmit () {
      const result = await purchaseFlowApi(this.approveObj)

      const stateIndex = this.stepList.findIndex(it => {
        return it.text === this.approveState
      }) + 1
      if (result.code === 200) {
        if (!this.approveObj.isReject) {
          // 如果选择的是通过
          this.list.map(it => {
            this.$toast.success(`${this.stepList[stateIndex].text}成功`)
            if (it.id === this.approveObj.id) {
              it.state = this.stepList[stateIndex].value
              this.approveState = it.state
              return it.state
            }
          })
        } else {
          // 如果是驳回
          this.$toast.success('驳回成功')
          const idx = this.list.findIndex(it => it.id === this.approveObj.id)
          const nowIdx = stateIndex - 2
          this.list[idx].state = this.stepList[nowIdx >= 0 ? nowIdx : 0].value
          this.approveState = this.list[idx].state
        }
      } else {
        this.$toast.fail(`${this.stepList[stateIndex].text}失败`)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '../../style/common.less';
 .my-header {
     display: flex;
     >input {
         flex: 1;
         border: none;
         outline: none;
         background-color: transparent;
         font-size: .7rem;
         text-indent: 14px;
     }
     > .icon {
         flex: 0 0 48px;
         background: url(../../images/search-icon.png) center center / 26px 26px no-repeat;
     }
 }
</style>
